package com.cogent.common.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.lang.StringUtils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64 {	
	private static final String cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/";
	private static final int fillchar = '=';
	
	public static String encode(String data) {
		if(StringUtils.isEmpty(data))
			return "";
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data.getBytes());
	}
	
	public static String encodeUtf8(String data) {
		if(StringUtils.isEmpty(data))
			return "";
		BASE64Encoder encoder = new BASE64Encoder();
		//encoder
		try {
			return encoder.encode(data.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	public static String decode(String data) {
		if(StringUtils.isEmpty(data)){
	        return "";
	    }
	    BASE64Decoder decoder = new BASE64Decoder();
	    try{
            data = new String(decoder.decodeBuffer(data));
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
        return data;
	}
	
	public static byte[] decodeBase64Byte(String data) {
		if(StringUtils.isEmpty(data))
			return null;
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			return decoder.decodeBuffer(data);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;		  
	}

	public static String encodeBase64(byte[] data) {
		if(data == null)
			return "";
		int c;
		int len = data.length;
		StringBuffer ret = new StringBuffer(((len / 3) + 1) * 4);
		for (int i = 0; i < len; ++i) {
			c = (data[i] >> 2) & 0x3f;
			ret.append(cvt.charAt(c));
			c = (data[i] << 4) & 0x3f;
			if (++i < len) {
				c |= (data[i] >> 4) & 0x0f;

			}
			ret.append(cvt.charAt(c));
			if (i < len) {
				c = (data[i] << 2) & 0x3f;
				if (++i < len) {
					c |= (data[i] >> 6) & 0x03;

				}
				ret.append(cvt.charAt(c));
			} else {
				++i;
				ret.append((char) fillchar);
			}

			if (i < len) {
				c = data[i] & 0x3f;
				ret.append(cvt.charAt(c));
			} else {
				ret.append((char) fillchar);
			}
		}
		return ret.toString();
	}
}
